package com.bookstore.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DBConnection {

	private static String user;
	private static String password;
	private static String url;

	static {
		try {
			ClassLoader classLoader = DBConnection.class.getClassLoader();
			InputStream is = classLoader.getResourceAsStream("config/props/db.properties");
			Properties properties = new Properties();
			properties.load(is);
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("password");
			Class.forName(properties.getProperty("driver"));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() throws Exception {
		return DriverManager.getConnection(url, user, password);
	}

	public static void close(ResultSet resultSet, Statement statement, Connection connection) throws Exception {
		if (resultSet != null) {
			resultSet.close();
		}
		if (statement != null) {
			statement.close();
		}
		if (connection != null) {
			connection.close();
		}
	}

	public static void close(Statement statement, Connection connection) throws Exception {
		if (statement != null) {
			statement.close();
		}
		if (connection != null) {
			connection.close();
		}
	}
}
